from django.shortcuts import render,HttpResponse
from .geetest import GeetestLib
from rest_framework.views import APIView
from rest_framework.generics import CreateAPIView
from rest_framework.response import Response
from .utils import get_user_by_account
from rest_framework import status as http_status
from .serializers import UserModelSerializer
from .models import User
import random
# Create your views here.


pc_geetest_id = "5e876edb2bda195c265416b70e7389a7"
pc_geetest_key = "c1f0f6f5958507924d187db31cd136e5"

class CaptchaAPIView(APIView): #滑动效验
    status = 1
    user_id = 'test'

    def get(self, request):
        username = request.query_params.get('username')
        user = get_user_by_account(username)

        if user is None:
            return Response({'msg': '找不到该用户'}, status=400)

        self.user_id = user.id

        gt = GeetestLib(pc_geetest_id, pc_geetest_key)
        self.status = gt.pre_process(self.user_id)

        response_str = gt.get_response_str()
        return HttpResponse(response_str)

    def post(self, request):

        gt = GeetestLib(pc_geetest_id, pc_geetest_key)
        challenge = request.data.get(gt.FN_CHALLENGE, '')
        validate = request.data.get(gt.FN_VALIDATE, '')
        seccode = request.data.get(gt.FN_SECCODE, '')

        if self.status:
            result = gt.success_validate(challenge, validate, seccode, self.user_id)
        else:
            result = gt.failback_validate(challenge, validate, seccode)
        result = {"status": "success"} if result else {"status": "fail"}
        return Response(result)

from rest_framework import status
class MobileAPIView(APIView):    # 验证手机号是否已经注册

    def get(self, request, mobile):
        import re
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return Response({"message":"⼿机号错误"}, status=status.HTTP_400_BAD_REQUEST)

        user = get_user_by_account(mobile)

        if user:
            return Response({"message":"⼿机号已经被注册过！"}, status=status.HTTP_400_BAD_REQUEST)
        return Response({"msg": "ok"})


class UserAPIView(CreateAPIView):     # 添加用户
    queryset = User.objects.all()
    serializer_class = UserModelSerializer


class SMSAPIView(APIView):
    """
    注册 获取验证码
    """

    def get(self, request, mobile):
        from django_redis import get_redis_connection
        redis_conn = get_redis_connection('sms_code')


        check_ret = redis_conn.get(f"mobile_{mobile}")
        if check_ret:
            return Response({"MSG": "等着先"}, status=http_status.HTTP_500_INTERNAL_SERVER_ERROR)

        try:
            redis_conn = get_redis_connection('sms_code')
            redis_conn.get(f'sms_{mobile}')

            sms_code = "%06d" % random.randint(0, 999999)
            from luffyapi.settings import constants

            pipe = redis_conn.pipeline()
            pipe.multi() #批量操作
            pipe.setex(f'sms_{mobile}', constants.SMS_EXPIRE_TIME, sms_code)
            pipe.setex(f'mobile_{mobile}', constants.SMS_INTREVAL_TIME, "_") #时间间隔
            pipe.execute() #执行

            # 调用容联云的发送短信
            from luffyapi.libs.yuntongxun import sms
            ccp = sms.CCP()
            ret = ccp.send_template_sms(mobile, [sms_code, constants.SMS_EXPIRE_TIME//60], 1)
            if not ret:
                return Response({"MSG": "短信发送失败"}, status=http_status.HTTP_500_INTERNAL_SERVER_ERROR)
            return Response({"MSG": "短信发送成功"})
        except:
            return Response({"MSG": "服务器内部错误",}, status=http_status.HTTP_500_INTERNAL_SERVER_ERROR)

